//
//  PYCaptureViewController.m
//  PictureYourself
//
//  Created by Daniel on 6/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PYCaptureViewController.h"
#import "PYCaptureSessionManager.h"

@implementation PYCaptureViewController

@synthesize capturedImageViewController = capturedImageViewController_;

#pragma mark Intialization

-(void)performFirstEverInitialization
{
    /* Check if this is our first ever launch on the device, and if so, set up some hints */
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL showHint = [userDefaults boolForKey:kShowHintTapAnywhere];
    NSLog(@"Got bool value for %@: %d\n", kShowHintTapAnywhere, showHint);
    
    if(showHint)
    {
        tapAnywhereMessageView_.hidden = FALSE;
        tapAnywhereImageView_.hidden = FALSE;
        
        [UIView animateWithDuration:0.75
                         animations:^(void)
         {
             tapAnywhereMessageView_.alpha = 1;
             tapAnywhereImageView_.alpha = 1;
         }];
        
        //NSLog(@"Tap anyhwere image's current bounds: %f, %f, %f x %f\n", tapAnywhereImageView_.bounds.origin.x, tapAnywhereImageView_.bounds.origin.y, tapAnywhereImageView_.bounds.size.width, tapAnywhereImageView_.bounds.size.height);
        
        //NSLog(@"Set tap anyhwere image's bounds to: %f, %f, %f x %f\n", tapAnywhereImageView_.bounds.origin.x, tapAnywhereImageView_.bounds.origin.y, tapAnywhereImageView_.bounds.size.width, tapAnywhereImageView_.bounds.size.height);
    }

}

-(void)performOutletInitialization
{
    [self.view addGestureRecognizer:tapGestureRecognizer_];
    
    UIScreen *screen = [UIScreen mainScreen];
    
    imageCountViewCenter_ = imageCountView_.center;
    imageCountViewSize_ = imageCountView_.bounds.size;
    [imageCountView_ setCenter:CGPointMake(screen.bounds.size.width + imageCountView_.bounds.size.width, imageCountViewCenter_.y)];
    imageCountButton_.imageCount = [PYCaptureSessionManager instance].imageToCaptureCount;
    imageCountSlider_.value = [PYCaptureSessionManager instance].imageToCaptureCount;//[[imageCountLabel_ text] integerValue];

    [galleryButton_.layer setCornerRadius:3.0];
    [galleryButton_.layer setMasksToBounds:TRUE];
    [galleryButton_.layer setBorderWidth:0.5];
    
    [self setGalleryThumbnail];
    
    NSString *toolbarBackgroundPath = [[NSBundle mainBundle] pathForResource:@"ToolbarGradientBackground" ofType:@"png"];
    UIImage *toolbarBackground = [UIImage imageWithContentsOfFile:toolbarBackgroundPath];
    UIColor *backgroundColor = [UIColor colorWithPatternImage:toolbarBackground];
    [toolbar_ setBackgroundColor:backgroundColor];
}

-(void)setGalleryThumbnail
{
    NSDictionary* properties;
    CGImageRef image = [[PYFileManager instance] copyLatestThumbnail :&properties];
    
    if(image)
    {
        UIImageOrientation orientation = uiImageOrientationToApply((CFDictionaryRef)properties);
        //[galleryButton_ setThumbnail:image :orientation];
        UIImage* thumbnailImage = [UIImage imageWithCGImage:image scale:1.0 orientation:orientation];
        [galleryButton_ setImage:thumbnailImage forState:UIControlStateNormal];
        CGImageRelease(image);
    }
}

- (void)viewDidLoad
{
    [self performOutletInitialization];
    [self performFirstEverInitialization];

    previewLayer_ = [[PYCaptureSessionManager instance] setVideoPreviewView:previewView_];
    [previewLayer_ setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [PYCaptureSessionManager instance].delegate = self;
}

#pragma mark - Actions

-(IBAction)imageCountButtonWasClicked:(id)sender
{
    [self setImageCountViewDisplay:imageCountView_.hidden];
}

-(IBAction)imageGalleryButtonWasClicked:(id)sender
{
    PYImageGalleryViewController* gallery_controller = [[PYImageGalleryViewController alloc] initWithNibName:@"PYImageGalleryView" bundle:nil];
    gallery_controller.delegate = self;
    
    UINavigationController* navigation_controller = [[UINavigationController alloc] initWithRootViewController:gallery_controller];
    navigation_controller.toolbarHidden = FALSE;
    navigation_controller.toolbar.barStyle = UIBarStyleBlackTranslucent;
    navigation_controller.navigationBarHidden = FALSE;
    navigation_controller.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self presentModalViewController:navigation_controller animated:TRUE];
    [navigation_controller release];
    [gallery_controller release];
}

-(void)setImageCountViewDisplay:(BOOL)shown
{
    if(shown)
    {
        imageCountView_.hidden = FALSE;
        
        [UIView animateWithDuration:0.5
            animations:^(void)
            {
                imageCountView_.center = imageCountViewCenter_;
            }
            completion:^(BOOL finished)
            {
            }];
    }
    else
    {
        [UIView animateWithDuration:0.5
            animations:^(void)
             {
                 UIScreen *screen = [UIScreen mainScreen];
                 imageCountView_.center =CGPointMake(screen.bounds.size.width + imageCountView_.bounds.size.width, imageCountViewCenter_.y);
             }
            completion:^(BOOL finished)
             {
                 //NSLog(@"UIView animation completion block was called. Finished: %d\n", finished);
                 imageCountView_.hidden = TRUE;
                 
                 // Save the image count as the user's default
                 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                 [userDefaults setInteger:[PYCaptureSessionManager instance].imageToCaptureCount forKey:kCaptureCount];
                 [userDefaults synchronize];
             }];    
    }
    
    return;
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
    imageCountView_.hidden = TRUE;
    NSLog(@"Animation did stop\n");
}

-(IBAction)sliderWasSlid:(id)sender
{
    NSLog(@"Slider value changed to %f\n", imageCountSlider_.value);
    imageCountSlider_.value = round(imageCountSlider_.value);
    //imageCountLabel_.text = [NSString stringWithFormat:@"%d", (int)imageCountSlider_.value];
    imageCountButton_.imageCount = imageCountSlider_.value;
    [PYCaptureSessionManager instance].imageToCaptureCount = imageCountSlider_.value;
    NSLog(@"Rounded slider value to %f\n", imageCountSlider_.value);
}

-(IBAction)sliderDoneSliding:(id)sender
{
    
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if(gestureRecognizer == tapGestureRecognizer_)
    {
        NSLog(@"Type of tap gesture view: %@\n", [touch.view class]);
        
        if(touch.view != previewView_)
            return FALSE;

        if([touch.view isKindOfClass:[UIButton class]])
            return FALSE;
    }
    
    return TRUE;
}

-(IBAction)tapWasRecognized:(id)sender
{
    // If the image count toolbar is displayed, just hide it and exit
    if(!imageCountView_.hidden)
    {
        [self setImageCountViewDisplay:FALSE];
        return;
    }
    
    NSLog(@"Caught a tap\n");
    
    [self shoot];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:FALSE forKey:kShowHintTapAnywhere];
    
    NSLog(@"Set value %@ to %d\n", kShowHintTapAnywhere, FALSE);
    
    [self hideTapAnywhereHint];
}

#pragma mark Capture Manager Delegation

-(void)imageCaptureCompleted
{
    dispatch_async(dispatch_get_main_queue(), ^(void)
                   {
                       progress_view_.progress = 0.0;
                       progress_view_.hidden = FALSE;
                       
                       [UIView animateWithDuration:0.75
                                        animations:^(void)
                        {
                            progress_view_.alpha = 1.0;
                        }];
                   });
}

-(void)setProgress:(NSUInteger)number
{
    float total_count = (float)[PYCaptureSessionManager instance].imageToCaptureCount;
    progress_view_.progress = 1.0 - ((float)number / total_count);
    NSLog(@"Set progress to %f\n", progress_view_.progress);
}

-(void)imageRemainingToSaveCountChangedTo:(NSUInteger)new_count
{
    NSLog(@"imageRemainingToSaveCountChangedTo START\n");
    //NSNumber* image_remaining = [NSNumber numberWithInt:new_count];
    //[self performSelectorOnMainThread:@selector(setProgress:) withObject:nil waitUntilDone:FALSE];
    //NSLog(@"imageRemainingToSaveCountChangedTo END\n");
    //NSLog(@"Current thread is Main thread: %d\n", [NSThread currentThread] == [NSThread mainThread]);
    
    
    float total_count = (float)[PYCaptureSessionManager instance].imageToCaptureCount;
    float progress = 1.0 - ((float)new_count / total_count);
    //NSLog(@"Calculated progress to: %f\n", progress);
    
    dispatch_async(dispatch_get_main_queue(), ^
    {
        [progress_view_ setProgress:progress];
        NSLog(@"Set progress to %f\n", progress_view_.progress);
    });
}

#pragma mark Gallery Controller Delegation

-(void)userIsDoneViewingGallery
{
    [self dismissModalViewControllerAnimated:TRUE];
}

#pragma mark Controller Methods

-(void)hideTapAnywhereHint
{
    [UIView 
        animateWithDuration:0.9
        animations:^(void)
         {
             tapAnywhereMessageView_.alpha = 0;
             tapAnywhereImageView_.alpha = 0;
         }         
        completion:^(BOOL finished)
         {
             tapAnywhereMessageView_.hidden = TRUE;
         }];
}

-(void)shoot
{
    //NSLog(@"Picture button pressed\n");
    
    PYCaptureSessionManager *captureManager = [PYCaptureSessionManager instance];
    
    [captureManager takePicturesWith:^(CGImageRef new_image)
     {
         NSLog(@"Block after 'takePicturesWith' called\n");
         
         dispatch_async(dispatch_get_main_queue(), ^(void)
                        {
                            [UIView animateWithDuration:0.75
                                             animations:^(void)
                             {
                                 progress_view_.alpha = 0.0;
                             }
                                             completion:^(BOOL finished)
                             {
                                 progress_view_.hidden = TRUE;
                             }];
                            
                            //galleryButton_.thumbnail = new_image;
                            [self setGalleryThumbnail];
                        });
     }
     ];
    
    NSLog(@"Called takePicture method\n");
}

#pragma mark View Controller Lifetime

- (void)didReceiveMemoryWarning 
{
    NSLog(@"Received memory warning on PYCaptureViewController !!!!!!!!!!!!!!!!!!!!!!!\n");
    [super didReceiveMemoryWarning];
}

-(void)dealloc
{
    [super dealloc];
    [previewLayer_ release];
}

@end

